package com.example.fastshareapp;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import org.alljoyn.bus.BusObject;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.location.Address;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.MediaStore.Images;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

enum DATASENDINGSTATUS {
	NONE, SENDING, DONE, ERROR
}

public class Utilities {

	public synchronized static Bitmap getImageLocal(String filePath) {
		return getImageLocal(filePath, BitmapUtil.REQUEST_WIDTH,
				BitmapUtil.REQUEST_HEIGHT);
	}

	public synchronized static Bitmap getImageLocal(String filePath,
			int reqWidth, int reqHeight) {
		if (reqWidth == -1 || reqHeight == -1) { // no subsample and no
			return BitmapFactory.decodeFile(filePath);
		} else {
			// First decode with inJustDecodeBounds=true to check dimensions
			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(filePath, options);

			// Calculate inSampleSize
			options.inSampleSize = BitmapUtil.calculateInSampleSize(options,
					reqWidth, reqHeight);

			// Decode bitmap with inSampleSize set
			options.inJustDecodeBounds = false;

			return BitmapFactory.decodeFile(filePath, options);
		}
	}

	public synchronized static Bitmap getImageLocal(String filePath, int percent) {
		if (percent > 90) { // no subsample and no
			return BitmapFactory.decodeFile(filePath);

		} else {
			// First decode with inJustDecodeBounds=true to check dimensions
			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(filePath, options);
			// Calculate inSampleSize
			options.inSampleSize = BitmapUtil.calculateInSampleSize(options,
					percent);
			// Decode bitmap with inSampleSize set
			options.inJustDecodeBounds = false;
			return BitmapFactory.decodeFile(filePath, options);
		}
	}

	public static byte[] getImageData(Bitmap image) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
		byte[] byteArray = stream.toByteArray();
		return byteArray;
	}

	public synchronized static String EncodeFromString(String data) {
		return Base64.encodeToString(data.getBytes(), Base64.DEFAULT);
	}

	public synchronized static String EncodeFromImage(Bitmap image) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 50, stream);
		byte[] byteArray = stream.toByteArray();
		return Base64.encodeToString(byteArray, Base64.DEFAULT);
	}

	public synchronized static String DecodeToString(String data)
			throws UnsupportedEncodingException {
		return new String(Base64.decode(data, Base64.DEFAULT), "UTF-8");
	}

	public synchronized static Bitmap DecodeToImage(String data) {
		byte[] image = Base64.decode(data, Base64.DEFAULT);
		return BitmapFactory.decodeByteArray(image, 0, image.length);
	}

	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	static class BitmapUtil {
		public static final int REQUEST_WIDTH = 180;
		public static final int REQUEST_HEIGHT = 120;

		public synchronized static int calculateInSampleSize(
				BitmapFactory.Options options) {
			return calculateInSampleSize(options, REQUEST_WIDTH, REQUEST_HEIGHT);
		}

		public synchronized static int calculateInSampleSize(
				BitmapFactory.Options options, int reqWidth, int reqHeight) {

			// Raw height and width of image
			final int height = options.outHeight;
			final int width = options.outWidth;
			int inSampleSize = 1;

			if (height > reqHeight || width > reqWidth) {
				// Calculate ratios of height and width to requested height and
				// width
				final int heightRatio = Math.round((float) height
						/ (float) reqHeight);
				final int widthRatio = Math.round((float) width
						/ (float) reqWidth);

				// Choose the smallest ratio as inSampleSize value, this will
				// guarantee
				// a final image with both dimensions larger than or equal to
				// the
				// requested height and width.
				inSampleSize = heightRatio < widthRatio ? heightRatio
						: widthRatio;
			}
			return inSampleSize;
		}

		public synchronized static int calculateInSampleSize(
				BitmapFactory.Options options, int percent) {

			// Raw height and width of image
			final int height = options.outHeight;
			final int width = options.outWidth;
			int inSampleSize = 1;

			if (percent < 100 && (height > 800 || width > 1000)) {
				// Calculate ratios of height and width to requested height and
				// width
				float reqHeight = height * percent / 100;
				float reqWidth = width * percent / 100;
				final int heightRatio = Math.round((float) height
						/ (float) reqHeight);
				final int widthRatio = Math.round((float) width
						/ (float) reqWidth);

				// Choose the smallest ratio as inSampleSize value, this will
				// guarantee
				// a final image with both dimensions larger than or equal to
				// the
				// requested height and width.
				inSampleSize = heightRatio < widthRatio ? heightRatio
						: widthRatio;
			}

			return inSampleSize;
		}

		public synchronized static List<Image> getListImageToSend(String name,
				byte[] data) {
			int dataSize = data.length;
			final int MAXSIZE = 100000;
			List<Image> result = new ArrayList<Image>();
			if (dataSize <= MAXSIZE) {
				Image image = new Image(name, 1, data);
				result.add(image);
				return result;
			}
			int totalPart = dataSize / MAXSIZE + 1;
			int begin = 0;
			int end = MAXSIZE;
			for (int i = 0; i < totalPart; i++) {
				Image image = new Image(name, i + 1, Arrays.copyOfRange(data,
						begin, end));
				begin += MAXSIZE;
				if (dataSize - end > MAXSIZE) {
					end += MAXSIZE;
				} else {
					end += dataSize - end;
				}
				result.add(image);
			}
			return result;
		}
		public synchronized static Bitmap getBitmapFromList(List<Image> _listImage, String name){
			byte[] imageData = new byte[0];
			for (Image image : _listImage) {
				if(image.getM_name().equals( name)){
					imageData = addTwoArrays(imageData, image.getM_data());
				}
			}
			return BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
		}
		
		private static byte[] addTwoArrays(byte[] a, byte[] b){
			byte[]result = new byte[a.length + b.length];
			System.arraycopy(a, 0, result, 0, a.length);
			System.arraycopy(b, 0, result, a.length, b.length);
			return result;
		}
	}
}
